package org.sundatagroup.aurora.monitor.controller;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.sundatagroup.aurora.core.controller.IJsonResultController;
import org.sundatagroup.aurora.monitor.service.MonitorService;
import org.sundatagroup.aurora.monitor.service.ScreenBatches;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

/**
 * <p>监控区主页 WebSocket 控制器, 
 * 该控制器处理服务器端发起的, 发送到前端的请求
 * </p>
 * 
 * @author Zdream
 * @date 2018-06-25
 * @version 0.2.0
 */
@Component
public class MonitorWebSocketController implements IJsonResultController {
	
	@Autowired
	ScreenBatches querier; // 展示区

	@Autowired
	MonitorService service;

	/**
	 * 向指定前端发送全部展示屏状态数据
	 * @param session
	 */
	public void allStatus(WebSocketSession session) {
		JsonObject jo = rawResultJsonObject(true);
		jo.addProperty("type", "sysnc-status-all");
		jo.add("data", querier.transformAll());
		
		try {
			session.sendMessage(new TextMessage(jo.toString()));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 主动向监控前端推送修改的状态数据
	 * @param sid
	 *   屏幕号
	 * @param status
	 *   屏幕状态, 不允许为 null
	 */
	public void pushStatus(String sid, JsonObject data) {
		JsonObject jo = rawResultJsonObject(true);
		jo.addProperty("type", "sysnc-status");
		jo.add("data", data);
		
		service.publishToMonitors(jo);
	}
	
	/**
	 * 主动向监控前端推送展示屏建立的消息
	 * @param sid
	 *   屏幕号
	 */
	public void pushScreenCreate(JsonObject data) {
		JsonObject jo = rawResultJsonObject(true);
		jo.addProperty("type", "sysnc-screen-create");
		jo.add("data", data);
		
		service.publishToMonitors(jo);
	}
	
	/**
	 * 主动向监控前端推送展示屏销毁的消息
	 * @param sid
	 *   屏幕号
	 */
	public void pushScreenDestroy(String sid) {
		JsonObject jo = rawResultJsonObject(true);
		jo.addProperty("type", "sysnc-screen-destroy");
		
		JsonObject data = new JsonObject();
		data.addProperty("sid", sid);
		jo.add("data", data);
		
		service.publishToMonitors(jo);
	}
	
	/**
	 * 成功查询
	 * @param session
	 * @param type
	 * @param data
	 */
	public void queryReturn(WebSocketSession session, String type, JsonElement data) {
		JsonObject jo = rawResultJsonObject(true);
		jo.addProperty("type", type);
		jo.add("data", data);
		
		try {
			session.sendMessage(new TextMessage(jo.toString()));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 失败查询
	 * @param session
	 * @param type
	 */
	public void queryReturnFall(WebSocketSession session, String type) {
		JsonObject jo = rawResultJsonObject(false);
		jo.addProperty("type", type);
		
		try {
			session.sendMessage(new TextMessage(jo.toString()));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
